Blog
Matlab syntax tricks

By Raphaël - December 18th, 2016

Matlab

0 Comment

The !(bang) operator

Styling command window output

Last but not least, here is a trick that many Matlab programmers ignore: the command line can be styled. If you always thought that the command line was dull, take a quick look at what follows and let your imagination do the rest!

Hyperlinks

Probably the most useful syntax trick in this section is the ability to insert an hyperlink in any command line output. Importantly, not only this hyperlink can open a web page in a browser, it can also execute some arbitrary matlab code upon clicking. The syntax is simple, it ressembles standard html:

fprintf('Click <a href="matlab:rand(3)">here</a> !\n');

And you should see:

Click here! ans = 0.8147 0.9134 0.2785 0.9058 0.6324 0.5469 0.1270 0.0975 0.9575

Here is a slightly more complex example:

fprintf('Click <a href="matlab:fprintf(''Thanks for clicking.\\n'');">here</a> !\n');

And you should see:

Click here! Thanks for clicking.

Note the double single quotes and the double backslash to escape the string and the newline character.

Styling text

It is also possible to render bold text by using the strong tag:

fprintf('This is <strong>bold</strong>\n');

On the color side, it is amazingly easy to obtain orange and red, as they are hardcoded for displaying warnings and errors. For orange you can use the [\b...]\b syntax:

fprintf('This is [\borange]\b.\n');

and for red, you can use the standard error channel (fid=2):

fprintf(2, 'Some text in red.\n');

Unfortunately there are many limitations: it is not possible to render italics, one cannot have a bolded hyperlink (if both tags are present, only the inner tag is taken into account) and other colors are not easily accesible. Following the work of Yair Altman (e.g. see here and his cprintf function), I've coded my own function ML.CW.printto render rich text in the command window. It is freely available in MLab, so give it a try ;-)

All the previous exemples also work without the java virtual machine, e.g. when ones run maltlab from the terminal without the -nodesktop option, except Yair Altman's cprintf that will only work within Matlab's IDE.

Have fun!

The !(bang) operator

Comments

No comments on this post so far.

Leave a comment

SEND